import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:activity_record/my_flutter_app_icons.dart';
import 'package:activity_record/ui/image_picked.dart';
import 'package:activity_record/ui/upload_task.dart';
//import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:activity_record/model/diy.dart';
import 'package:activity_record/model/diy_image.dart';
import 'package:activity_record/model/diy_project.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
//import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
//import 'package:transparent_image/transparent_image.dart';

/*
diy活动新增页面
涉及用户输入所以继承自状态可变的StatefulWidget
采用全屏对话框的形式展现
 */
class DiyAddDialog extends StatefulWidget {
  DiyAddDialog({Key key, @required this.db, this.diy}) : super(key: key);
  final db;
  final Diy diy;

  @override
  DiyAddDialogState createState() => new DiyAddDialogState();
}

class DiyAddDialogState extends State<DiyAddDialog> {
  String _title = '';
  String _path = '';
//实例化对象已选择的时间，并赋予初始值是当前时间
  // String _selectedDate = DateFormat.yMd("en_US").format(DateTime.now());
  //图片上传任务列表
  // List<StorageUploadTask> _upLoadTask = [];
  //存放firestorage返回的图片下载地址
  List<String> _imageUrls = [];
  List<DiyImage> _imageDatas = [];
  // //存放建议活动名称库
  // List<String> _nameSuggestions = [];
  // //存放建议联系人库
  // List<String> _contractSuggestions = [];
  bool _isPaided = false;
  String _selectedDate = DateFormat('yyyy-MM-dd').format(DateTime.now());
  int year = DateTime.now().year;
  int month = DateTime.now().month;
  int date = DateTime.now().day;
  //活动名称输入框控制器
  TextEditingController _nameTextEditingController =
      new TextEditingController();
  //活动地点输入框控制器
  TextEditingController _placeTextEditingController =
      new TextEditingController();
  //活动联系人输入框控制器
  TextEditingController _contactTextEditingController =
      new TextEditingController();
  //活动单价输入框控制器
  TextEditingController _singlePriceTextEditingController =
      new TextEditingController();
  //活动份数输入框控制器
  TextEditingController _numsTextEditingController =
      new TextEditingController();
  //活动物料成本输入框控制器
  TextEditingController _itemCostTextEditingController =
      new TextEditingController();
  //活动人员成本输入框控制器
  TextEditingController _laborCostTextEditingController =
      new TextEditingController();
  //备注输入框控制器
  TextEditingController _notesTextEditingController =
      new TextEditingController();
  FocusNode _noteFocusNode = new FocusNode();
  FocusNode _placeFocusNode = new FocusNode();
  FocusNode _contactFocusNode = new FocusNode();
  FocusNode _singlePriceFocusNode = new FocusNode();
  FocusNode _numFocusNode = new FocusNode();
  FocusNode _itemCostFocusNode = new FocusNode();
  FocusNode _laborCostFocusNode = new FocusNode();

  @override
  void dispose() {
    _nameTextEditingController.dispose();
    _placeTextEditingController.dispose();
    _contactTextEditingController.dispose();
    _singlePriceTextEditingController.dispose();
    _numsTextEditingController.dispose();
    _itemCostTextEditingController.dispose();
    _laborCostTextEditingController.dispose();
    _notesTextEditingController.dispose();
    super.dispose();
  }

  //获得应用文档目录
  _getPath() async {
    final Directory _directory = await getApplicationDocumentsDirectory();
    final Directory _imageDirectory =
        await new Directory('${_directory.path}/image/')
            .create(recursive: true);
    _path = _imageDirectory.path;
    print('本次获得路径：${_imageDirectory.path}');
  }

  //根据是否传入diyProject进行输入控件内容的初始化
  @override
  void initState() {
    super.initState();
    _getPath();
    if (widget.diy != null) {
      _selectedDate = widget.diy.diyProject.date;
      _nameTextEditingController.text = widget.diy.diyProject.name;
      _placeTextEditingController.text = widget.diy.diyProject.place;
      _contactTextEditingController.text = widget.diy.diyProject.contact;
      _singlePriceTextEditingController.text =
          widget.diy.diyProject.singlePrcie.toString();
      _numsTextEditingController.text = widget.diy.diyProject.nums.toString();
      _itemCostTextEditingController.text =
          widget.diy.diyProject.itemCost.toString();
      _laborCostTextEditingController.text =
          widget.diy.diyProject.laborCost.toString();
      _isPaided = widget.diy.diyProject.isPaided;
      _notesTextEditingController.text = widget.diy.diyProject.notes;
      widget.diy.imageDatas.forEach((value) {
        _imageUrls
            .add(value.imageUrl.substring(value.imageUrl.lastIndexOf('/')+1));
        print('999999999999999${_imageUrls.first}');
      });
    }
  }

  //点击保存或更新的时候如果未选取图片则弹出对话框提示
  _noImageDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return new AlertDialog(
            title: new Text('请至少添加一张活动样张'),
            actions: <Widget>[
              new FlatButton(
                child: new Text('确定'),
                onPressed: () => Navigator.of(context).pop(null),
              )
            ],
          );
        });
  }

  //IOS风格的日期选择器
  void _showDatePicker(BuildContext context) {
    final bool showTitleActions = true;
    DatePicker.showDatePicker(
      context,
      showTitleActions: showTitleActions,
      minYear: 1970,
      maxYear: 2050,
      initialYear: year,
      initialMonth: month,
      initialDate: date,
      locale: 'zh',
      dateFormat: 'yyyy-mmm-dd',
      onConfirm: (year, month, date) {
        _settingDatetime(year, month, date);
      },
    );
  }

  //进行根据选择的日期进行日期设置
  void _settingDatetime(int year, int month, int date) {
    setState(
      () {
        this.year = year;
        String m = month < 10 ? '0$month' : month.toString();
        String d = date < 10 ? '0$date' : date.toString();

        _selectedDate = '$year-$m-$d';
      },
    );
  }

  //活动文字信息输入
  Widget _infoTextField(
    BuildContext context,
    TextEditingController controller,
    Icon icon,
    String label,
    Diy diy, {
    FocusNode focusNode,
    TextInputAction textInput: TextInputAction.done,
    VoidCallback callBack,
  }) {
    return new Theme(
      data: new ThemeData(
          primaryColor: Colors.grey[600], hintColor: Colors.grey[600]),
      child: new TextField(
        onEditingComplete: callBack,
        focusNode: focusNode,
        autofocus: diy == null ? true : false,
        controller: controller,
        textInputAction: textInput,
        decoration: InputDecoration(
          hintText: label,
          prefixIcon: icon,
        ),
        cursorColor: Theme.of(context).primaryColor,
      ),
    );
  }

  //活动价格份数信息输入框封装
  Widget _amountTextField(
    TextEditingController controller,
    String labelText,
    String prefixText,
    String suffixText, {
    bool autoFocus: false,
    TextInputAction textInput: TextInputAction.done,
    VoidCallback callBack,
    FocusNode focusNode,
  }) {
    return new TextField(
      //键盘类型适用于登录的
      onEditingComplete: callBack,
      keyboardType: TextInputType.numberWithOptions(signed: true),
      controller: controller,
      autofocus: autoFocus,
      textInputAction: textInput,
      focusNode: focusNode,
      /*
      输入框装饰：
      包含边框、标题、提示文本、后缀文本
      */
      decoration: new InputDecoration(
          contentPadding: EdgeInsets.zero,
          labelText: labelText,
          prefixText: prefixText,
          suffixText: suffixText,
          suffixStyle: new TextStyle(color: Colors.green)),
    );
  }

  //多图选择器
  _pickImage() async {
    //通过MultiImagePicker插件从本地相册选取图片，配置一次最多选择12张，禁止摄像头拍照
    var requestList = await MultiImagePicker.pickImages(
      maxImages: 12,
      enableCamera: false,
    );
    if (!mounted) return;
    //这里进行一下判断，是否选择了图片，如果没有选择图片不进行任何操作。
    if (requestList.length != 0) {
      for (int i = 0; i < requestList.length; i++) {
        //获得一个uuud码用于给图片命名
        final String uuid = Uuid().v1();
        //请求原始图片数据
        await requestList[i].requestOriginal();
        //获取图片数据，并转换成uint8List类型
        Uint8List imageData = requestList[i].imageData.buffer.asUint8List();
        //通过图片压缩插件进行图片压缩
        var result =
            await FlutterImageCompress.compressWithList(imageData, quality: 90);
//        将压缩的图片暂时存入应用缓存目录
        File imageFile = new File('${_path}Image_$uuid.png')
          ..writeAsBytesSync(result);
        _imageUrls.add('Image_$uuid.png');
        print('图片地址是：${imageFile.path}');
        setState(() {});
      }
    }
  }

  //根据输入计算总金额
  _totalAmountCalculate() {
    int _totalAmount = int.parse(_singlePriceTextEditingController.text) *
        int.parse(_numsTextEditingController.text);
    return _totalAmount;
  }

  //根据输入计算利润
  _profitCalculate() {
    int totalAmount = _totalAmountCalculate();
    int _profit = totalAmount -
        int.parse(_itemCostTextEditingController.text == ''
            ? '0'
            : _itemCostTextEditingController.text) -
        int.parse(_laborCostTextEditingController.text == ''
            ? '0'
            : _laborCostTextEditingController.text);
    return _profit;
  }

  //根据选择计算未结钱款
  _unPaidAmountCalculate() {
    if (_isPaided) {
      return 0;
    } else {
      return _totalAmountCalculate();
    }
  }

  //先根据是否传入diyProject来判断是新增还是更新
  Future<Diy> _saveDiyItem(
      String name,
      String date,
      String place,
      String contact,
      int singlePrice,
      int nums,
      int totalAmount,
      int itemCost,
      int laborCost,
      int profit,
      int unPaidAmount,
      bool isPaided,
      String notes,
      List imageUrl) async {
    //如果该页面没有diyProject传进来，说明是从首页新增按钮进来，所以是新增
    if (widget.diy == null) {
      DiyProject newDiyProject = new DiyProject(
          name,
          date,
          place,
          contact,
          singlePrice,
          nums,
          totalAmount,
          itemCost,
          laborCost,
          profit,
          unPaidAmount,
          isPaided,
          notes);
      int savedID = await widget.db.insertDiyProject(newDiyProject);
      // print('插入的savedID：$savedID');
      var getDiyProjectResult = await widget.db.getDiyProject(savedID);
      for (int i = 0; i < imageUrl.length; i++) {
        _imageDatas.add(DiyImage(
          savedID,
          imageUrl[i],
        ));
      }
      for (int i = 0; i < _imageDatas.length; i++) {
        await widget.db.insertDiyImages(_imageDatas[i]);
        //  print('图片id:$savedImageID 已经插入，对应的diyId：${savedID}');
      }
      var getDiyProjectImages = await widget.db.getImageDatas(savedID);
      _imageDatas = [];
      for (var v in getDiyProjectImages) {
        _imageDatas.add(DiyImage.fromMap(v, _path));
      }
      return new Diy(getDiyProjectResult, _imageDatas);
    } else {
      //从数据库中删除原来选择的图片
      await widget.db.deleteImageDatas(widget.diy.diyProject.id);
      //根据页面内容实例化新的diy信息对象
      DiyProject diyProjectUpdated = DiyProject.fromMap({
        'id': widget.diy.diyProject.id,
        'name': _nameTextEditingController.text,
        'date': _selectedDate,
        'place': _placeTextEditingController.text,
        'contact': _contactTextEditingController.text,
        'singlePrice': int.parse(_singlePriceTextEditingController.text),
        'nums': int.parse(_numsTextEditingController.text),
        'totalAmount': _totalAmountCalculate(),
        'itemCost': int.parse(_itemCostTextEditingController.text),
        'laborCost': int.parse(_laborCostTextEditingController.text),
        'profit': _profitCalculate(),
        'unPaidAmount': _unPaidAmountCalculate(),
        'isPaided': _isPaided == true ? '1' : '0',
        'notes': _notesTextEditingController.text
      });
      //更新diy信息到数据库
      await widget.db.updateDiyProject(diyProjectUpdated);
      print('本次更新的名字是:${diyProjectUpdated.name}');
      //根据选择的图片实例化图片对象并添加到图片对象数组
      // _imagePickedForOriginal.forEach((imageU8List) {
      //   _imageDatas.add(DiyImage(widget.diy.diyProject.id, imageU8List));
      // });
      for (int i = 0; i < _imageUrls.length; i++) {
        _imageDatas.add(DiyImage(
          widget.diy.diyProject.id,
          _imageUrls[i],
        ));
      }
      //把新选择的图片添加到数据库
      for (int i = 0; i < _imageDatas.length; i++) {
        await widget.db.insertDiyImages(_imageDatas[i]);
      }
      var getDiyProjectImages =
          await widget.db.getImageDatas(widget.diy.diyProject.id);
      _imageDatas = [];
      for (var v in getDiyProjectImages) {
        _imageDatas.add(DiyImage.fromMap(v, _path));
      }
      return new Diy(diyProjectUpdated, _imageDatas);
    }
  }

  //保存、提交按钮点击方法
  void _pressSavedOrCommit(BuildContext context) {
    if (_imageUrls.length == 0) {
      _noImageDialog(context);
    } else
      Navigator.of(context).pop(_saveDiyItem(
          _nameTextEditingController.text,
          _selectedDate,
          _placeTextEditingController.text,
          _contactTextEditingController.text,
          int.parse(_singlePriceTextEditingController.text),
          int.parse(_numsTextEditingController.text),
          _totalAmountCalculate(),
          int.parse(_itemCostTextEditingController.text == ''
              ? '0'
              : _itemCostTextEditingController.text),
          int.parse(_laborCostTextEditingController.text == ''
              ? '0'
              : _laborCostTextEditingController.text),
          _profitCalculate(),
          _unPaidAmountCalculate(),
          _isPaided,
          _notesTextEditingController.text,
          _imageUrls));
  }

  //获取用户输入区域内容
  Widget buildBuilder() {
    return new Builder(
      builder: (BuildContext context) {
        return new SafeArea(
          top: false,
          //这个容器是用于当触���虚拟键盘后，点击区域内的空白地方转移焦点从而实现关闭虚拟键盘效果
          child: new Container(
            height: 1400.0,
            child: new GestureDetector(
              onVerticalDragCancel: () {
                FocusScope.of(context).requestFocus(FocusNode());
              },
              child: new ListView(
                children: <Widget>[
                  new Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16.0),
                    child: new Column(
                      children: <Widget>[
                        //日期选择框
                        new InkWell(
                          onTap: () => _showDatePicker(context),
                          child: new Container(
                            padding: const EdgeInsets.all(12.0),
                            child: new Row(
                              children: <Widget>[
                                new Icon(
                                  Xusj.data,
                                  // color: Theme.of(context).dividerColor,
                                  size: 24.0,
                                ),
                                new SizedBox(
                                  width: 12.0,
                                ),
                                new Text(
                                  _selectedDate,
                                  style: Theme.of(context)
                                      .textTheme
                                      .subhead
                                      .copyWith(fontWeight: FontWeight.normal),
                                ),
                              ],
                            ),
                          ),
                        ),
                        //活动名称输入框
                        new Theme(
                          data: new ThemeData(
                              primaryColor: Colors.grey[600],
                              hintColor: Colors.grey[600]),
                          child: new TextField(
                            onChanged: (String text) {
                              setState(
                                () {
                                  _title = text;
                                },
                              );
                            },
                            onEditingComplete: () => FocusScope.of(context)
                                .requestFocus(_placeFocusNode),
                            autofocus: widget.diy == null ? true : false,
                            controller: _nameTextEditingController,
                            textInputAction: TextInputAction.next,
                            decoration: InputDecoration(
                              hintText: ('活动名称'),
                              prefixIcon: new Icon(Icons.movie_filter),
                            ),
                            cursorColor: Theme.of(context).primaryColor,
                            // style: Theme.of(context).textTheme.title,
                          ),
                        ),
                        _infoTextField(
                          context,
                          _placeTextEditingController,
                          Icon(Icons.place),
                          '活动地点',
                          widget.diy,
                          focusNode: _placeFocusNode,
                          callBack: () => FocusScope.of(context)
                              .requestFocus(_contactFocusNode),
                          textInput: TextInputAction.next,
                        ),
                        _infoTextField(
                          context,
                          _contactTextEditingController,
                          Icon(Icons.nature_people),
                          '联系人',
                          widget.diy,
                          focusNode: _contactFocusNode,
                          callBack: () => FocusScope.of(context)
                              .requestFocus(_noteFocusNode),
                          textInput: TextInputAction.next,
                        ),
                        //备注输入框
                        _infoTextField(context, _notesTextEditingController,
                            Icon(Icons.subject), '备注', widget.diy,
                            focusNode: _noteFocusNode,
                            textInput: TextInputAction.next,
                            callBack: () => FocusScope.of(context)
                                .requestFocus(_singlePriceFocusNode)),
                      ],
                    ),
                  ),
                  new Container(
                    margin: const EdgeInsets.only(top: 18.0),
                    height: 8.0,
                    color: Theme.of(context).dividerColor,
                  ),
                  // new InkWell(
                  //   child: new Container(
                  //     height: 30.0,
                  //     child: new Column(),
                  //   ),
                  //   onTap: () {
                  //     showModalBottomSheet(
                  //         context: context,
                  //         builder: (BuildContext context) {
                  //           return new ListView(
                  //             children: <Widget>[
                  //               new Container(
                  //                 padding: const EdgeInsets.fromLTRB(
                  //                     16.0, 10.0, 16.0, 12.0),
                  //                 child: new Row(
                  //                   children: <Widget>[
                  //                     new Expanded(
                  //                       child: _amountTextField(
                  //                           _singlePriceTextEditingController,
                  //                           '单价(必填)',
                  //                           '\￥',
                  //                           'CNY',
                  //                           autoFocus: true),
                  //                     ),
                  //                     new SizedBox(
                  //                       width: 40.0,
                  //                     ),
                  //                     new Expanded(
                  //                       child: _amountTextField(
                  //                           _numsTextEditingController,
                  //                           '份数(必填)',
                  //                           '\￡',
                  //                           '份'),
                  //                     ),
                  //                   ],
                  //                 ),
                  //               ),
                  //               new Container(
                  //                 padding: const EdgeInsets.fromLTRB(
                  //                     16.0, 10.0, 16.0, 18.0),
                  //                 child: new Row(
                  //                   children: <Widget>[
                  //                     new Expanded(
                  //                       child: _amountTextField(
                  //                           _itemCostTextEditingController,
                  //                           '物料成本',
                  //                           '\￥',
                  //                           'CNY'),
                  //                     ),
                  //                     new SizedBox(
                  //                       width: 40.0,
                  //                     ),
                  //                     new Expanded(
                  //                       child: _amountTextField(
                  //                           _laborCostTextEditingController,
                  //                           '人员成本',
                  //                           '\￥',
                  //                           'CNY'),
                  //                     ),
                  //                   ],
                  //                 ),
                  //               ),
                  //               new Row(
                  //                 children: <Widget>[
                  //                   new Expanded(
                  //                     child: new RaisedButton(
                  //                       onPressed: () {},
                  //                       child: new Text('取消'),
                  //                       color: Theme.of(context)
                  //                           .primaryColor,
                  //                     ),
                  //                   ),
                  //                   new SizedBox(
                  //                     width: 30.0,
                  //                   ),
                  //                   new Expanded(
                  //                     child: new RaisedButton(
                  //                       onPressed: () {},
                  //                       child: new Text('确定'),
                  //                       color: Theme.of(context)
                  //                           .primaryColor,
                  //                     ),
                  //                   )
                  //                 ],
                  //               )
                  //             ],
                  //           );
                  //         });
                  //   },
                  // ),
                  //把两个金额输入框放在一个包含padding的横向布局里
                  new Container(
                    padding: const EdgeInsets.fromLTRB(16.0, 10.0, 16.0, 12.0),
                    child: new Row(
                      children: <Widget>[
                        new Expanded(
                          child: _amountTextField(
                            _singlePriceTextEditingController,
                            '单价(必填)',
                            '\￥',
                            'CNY',
                            focusNode: _singlePriceFocusNode,
                            textInput: TextInputAction.next,
                            callBack: () => FocusScope.of(context)
                                .requestFocus(_numFocusNode),
                          ),
                        ),
                        new SizedBox(
                          width: 40.0,
                        ),
                        new Expanded(
                          child: _amountTextField(
                            _numsTextEditingController,
                            '份数(必填)',
                            '\￡',
                            '份',
                            focusNode: _numFocusNode,
                            textInput: TextInputAction.next,
                            callBack: () => FocusScope.of(context)
                                .requestFocus(_itemCostFocusNode),
                          ),
                        ),
                      ],
                    ),
                  ),
                  //把两个金额输入框放在一个包含padding的横向布局里
                  new Container(
                    padding: const EdgeInsets.fromLTRB(16.0, 10.0, 16.0, 18.0),
                    child: new Row(
                      children: <Widget>[
                        new Expanded(
                          child: _amountTextField(
                            _itemCostTextEditingController,
                            '物料成本',
                            '\￥',
                            'CNY',
                            focusNode: _itemCostFocusNode,
                            textInput: TextInputAction.next,
                            callBack: () => FocusScope.of(context)
                                .requestFocus(_laborCostFocusNode),
                          ),
                        ),
                        new SizedBox(
                          width: 40.0,
                        ),
                        new Expanded(
                          child: _amountTextField(
                            _laborCostTextEditingController,
                            '人员成本',
                            '\￥',
                            'CNY',
                            focusNode: _laborCostFocusNode,
                          ),
                        ),
                      ],
                    ),
                  ),
                  new Container(
                    height: 8.0,
                    color: Theme.of(context).dividerColor,
                  ),
                  //欠款是否结清
                  new Padding(
                    padding: const EdgeInsets.fromLTRB(8.0, 0.0, 4.0, 0.0),
                    child: new CheckboxListTile(
                      value: _isPaided,
                      onChanged: (value) {
                        setState(
                          () {
                            _isPaided = value;
                          },
                        );
                      },
                      secondary: new Icon(
                        MyFlutterApp.wallet,
                        color:
                            _isPaided ? Theme.of(context).primaryColor : null,
                      ),
                      title: new Text('钱款已结清'),
                    ),
                  ),
                  new Container(
                    height: 8.0,
                    color: Theme.of(context).dividerColor,
                  ),
//                  没有选取照片时显示选取照片按钮，有照片显示已选取图片
                  _imageUrls.length == 0
                      ? new Padding(
                          padding:
                              const EdgeInsets.fromLTRB(22.0, 20.0, 22.0, 0.0),
                          child: new RaisedButton(
                            padding: const EdgeInsets.all(14.0),
                            onPressed: () => _pickImage(),
                            child: new Text(
                              '选取图片',
                              style: new TextStyle(
                                fontSize: 20.0,
                                color: Colors.white,
                              ),
                            ),
                            color: Theme.of(context).primaryColor,
                          ),
                        )
                      : buildImagePicked(context)
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  //通过图片选择器选择图片后的显示
  Widget buildImagePicked(BuildContext context) {
    return new Padding(
      padding: const EdgeInsets.all(16.0),
      child: new Wrap(
          spacing: 4.0,
          runSpacing: 4.0,
          alignment: WrapAlignment.start,
          children: List.generate((_imageUrls.length + 1), (index) {
            if (index != _imageUrls.length) {
              return new ImagePicked(
                imageUrl: _imageUrls[index],
                index: index,
                valueChanged: (index) {
                  setState(() {
                    _imageUrls.removeAt(index);
                  });
                },
                path: _path,
              );
            } else
              return new GestureDetector(
                onTap: () => _pickImage(),
                child: new Container(
                  color: Theme.of(context).dividerColor,
                  width: (MediaQuery.of(context).size.width - 32.0 - 8.0) / 3,
                  height: (MediaQuery.of(context).size.width - 32.0 - 8.0) / 3,
                  child: new Icon(
                    Icons.add,
                    size: 50.0,
                    color: Colors.grey,
                  ),
                ),
              );
          })),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new PreferredSize(
        preferredSize: Theme.of(context).platform == TargetPlatform.iOS
            ? new Size(0.0, 44.0)
            : new Size(0.0, 56.0),
        child: new AppBar(
          elevation:
              Theme.of(context).platform == TargetPlatform.iOS ? 1.0 : 4.0,
          title: new Text(_title),
          actions: <Widget>[
            new FlatButton(
              child: new Text(
                widget.diy == null ? '保存' : '提交',
                style: Theme.of(context)
                    .textTheme
                    .subhead
                    .copyWith(color: Theme.of(context).scaffoldBackgroundColor),
              ),
              onPressed: () {
                _pressSavedOrCommit(context);
              },
            )
          ],
        ),
      ),
      body: buildBuilder(), //新增项目的UI
//      child: new CustomScrollView(
//        slivers: <Widget>[
//          new SliverAppBar(
//            pinned: true,
//            elevation:
//                Theme.of(context).platform == TargetPlatform.iOS ? 1.0 : 4.0,
//            title: new Text(_title),
//            actions: <Widget>[
//              new FlatButton(
//                child: new Text(
//                  widget.diy == null ? '保存' : '提交',
//                  style: Theme.of(context).textTheme.subhead.copyWith(
//                      color: Theme.of(context).scaffoldBackgroundColor),
//                ),
//                onPressed: () {
//                  _pressSavedOrCommit(context);
//                },
//              )
//            ],
//          ),
//          new SliverSafeArea(
//            top: false,
//            sliver: new SliverList(
//              delegate: new SliverChildListDelegate([buildBuilder()]),
//            ),
//          ),
//          widget.diy ==null? _upLoadTask.length ==0?
//          new SliverGrid.count(
//            crossAxisCount: 3,
//            children: <Widget>[],
//          )
//        ],
//      ),
    );
  }
}
